package cn.chinawyny.boot.bootdemo.error;

import cn.chinawyny.boot.bootdemo.controller.HelloWorldController;
import cn.chinawyny.boot.bootdemo.exceptions.MyException;
import org.springframework.boot.web.servlet.DispatcherType;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(basePackageClasses = HelloWorldController.class)
public class MyErrorController extends ResponseEntityExceptionHandler {


    @ExceptionHandler(MyException.class)
    @ResponseBody
    public ResponseEntity<Object> handleControllerException(HttpServletRequest  request, Throwable ex) {
        HttpStatus status = getStatus(request);
        return new ResponseEntity<>(new MyErrorBody(status.value(), ex.getMessage()), status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        HttpStatus status = HttpStatus.resolve(code);
        return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
    }
}


